package com.zlp.test.utils;


import com.alibaba.fastjson.JSON;
import com.zlp.test.dto.Content;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j(topic = "JsoupUtil")
public class JsoupUtil {



    public List<Content> parseJD(String keyword) throws Exception {
        String url = "https://search.jd.com/Search?keyword="+keyword;
        //解析网页，返回值就是网页对象,30000是响应时间，随意设置
        Document document = Jsoup.parse(new URL(url), 30000);
        //参数为需要获取内容的class
        Element goodsList = document.getElementById("J_goodsList");
        Elements elements = goodsList.getElementsByTag("li");
        ArrayList<Content> contents = new ArrayList<>();
        for (Element element : elements) {
            String img = element.getElementsByTag("img").eq(0).attr("src");
            String price = element.getElementsByClass("p-price").eq(0).text();
            String title = element.getElementsByClass("p-name").eq(0).text();
            Content content = new Content(title, price, img);
            contents.add(content);
        }
        log.info("parseJD.resp contents={}", JSON.toJSONString(contents));
        return contents;
    }



}
